import { getOrderNetworkAddress, getWorkUserAddress } from '@/api/parts'
import { ref } from 'vue'
import {
  checkCode,
  engineerEndOrderApply,
  engineerTakeMaterialConfirm,
  getBeforeUpdateWorkUserInfo,
  getEndOrderFieldList,
  getOrderEndStatus,
  getOrderStatusQty,
  getWaitCheckOrderEvent,
  pushOrderToDianJiangYuan,
  queryCodeForUpdateCode,
  saveEndOrderResult,
  saveUpdateWorkUser,
  updateBaishiOrderStatus,
  updateWorkGoodsBindSnCode,
} from '@/api/order'

export const useGetOrderCustomerAddressByOrderId = () => {
  const getAddressLoading = ref(false)
  const address = ref<OrderCustomerAddress>({
    address: '',
    area: '',
    avatar: null,
    city: '',
    code: null,
    disabled: false,
    id: '',
    name: '',
    phone: '',
    province: '',
    qty: null,
    select: false,
    town: '',
    userName: null,
  })

  const getAddress = async (orderId: string) => {
    getAddressLoading.value = true
    const res = await getWorkUserAddress(orderId)
    address.value = res.data.data.row
    getAddressLoading.value = false
  }

  return {
    address,
    getAddressLoading,
    getAddress,
  }
}

export const useGetNetwordAddressByOrderId = () => {
  const getAddressLoading = ref(false)
  const address = ref({
    address: '',
    area: '',
    avatar: null,
    city: '',
    code: '',
    disabled: false,
    id: '',
    name: '',
    phone: '',
    province: '',
    qty: null,
    select: false,
    town: '',
    userName: null,
  })

  const getAddress = async (orderId: string) => {
    getAddressLoading.value = true
    const res = await getOrderNetworkAddress(orderId)
    address.value = res.data.data.row
    getAddressLoading.value = false
  }

  return {
    address,
    getAddressLoading,
    getAddress,
  }
}

/**
 * 获取待处理的工单事件
 */
export const useGetWaitHandleOrderEvent = () => {
  // 获取事件加载
  const getEventLoading = ref(false)

  // 待处理事件列表
  const waitHandleEventList = ref<Array<OrderWaitHandleEvent>>([])

  /**
   * 获取工单待处理的事件
   * @param {string} orderId - 工单id
   */
  const getWaitHandleEvent = async (orderId: string) => {
    getEventLoading.value = true
    const res = await getWaitCheckOrderEvent(orderId)
    getEventLoading.value = false
    if (res.data.code === 20000) {
      waitHandleEventList.value = res.data.data.rows
      return ''
    }
    return res.data.message
  }

  return {
    getEventLoading,
    waitHandleEventList,
    getWaitHandleEvent,
  }
}

/**
 * 审核条码
 */
export const useCheckCode = () => {
  // 审核加载
  const checkLoading = ref(false)

  // 审核表单
  const checkForm = ref({
    remark: '',
    checkResult: false,
  })

  /**
   * 审核
   * @param {string} orderId - 工单id
   */
  const check = async (orderId: string) => {
    checkLoading.value = true
    const res = await checkCode(checkForm.value, orderId)
    checkLoading.value = false
    return res.data
  }

  /**
   * 重置表单
   */
  const resetForm = () => {
    checkForm.value = {
      remark: '',
      checkResult: false,
    }
  }

  return {
    checkForm,
    checkLoading,
    check,
    resetForm,
  }
}

/**
 * 获取工单列表每个状态对应的工单数量
 */
export const useGetOrderListStatusQty = () => {
  // 获取数量加载
  const getOrderListStatusQtyLoading = ref(false)

  // 每个状态对应的工单数量
  const orderListStatusQty = ref<OrderListStatusQty>({
    cancelOrder: 0,
    feeWaitCheckQty: 0,
    finishOrder: 0,
    handlerOrder: 0,
    notOpenTicketCount: 0,
    notPaymentStatusCount: 0,
    openTicketCount: 0,
    openTicketTotalCount: 0,
    paymentStatusCount: 0,
    paymentStatusTotalCount: 0,
    snCodeWaitCheckCount: 0,
    spareWaitCheckQty: 0,
    statementReview: 0,
    totalOrder: 0,
    waitCallPhoneQty: 0,
    waitDispatch: 0,
    waitEngineerReceivingOrderQty: 0,
    waitNetworkDispatchOrderQty: 0,
    waitNetworkHandlerOrder: 0,
    waitNetworkReceivingOrderQty: 0,
    waitReservationQty: 0,
    waitSignQty: 0,
  })

  /**
   * 获取数量
   */
  const getOrderListStatusQty = async () => {
    getOrderListStatusQtyLoading.value = true
    const res = await getOrderStatusQty(10000, 1)
    getOrderListStatusQtyLoading.value = false
    if (res.data.code === 20000) {
      orderListStatusQty.value = res.data.data.row
      return ''
    }
    return res.data.message
  }

  return {
    orderListStatusQty,
    getOrderListStatusQtyLoading,
    getOrderListStatusQty,
  }
}

/**
 * 申请结单（网点角色使用）
 */
export const useEngineerEndOrderApply = () => {
  // 申请加载
  const applyLoading = ref(false)

  // 申请表单
  const applyForm = ref<OrderAPIRequest.EndOrderApply>({
    faultReason: [],
    faultRelationVos: [],
    faultTypeRelationVos: [],
    id: '',
    moduleId: '',
    remark: '',
    reviewRemark: '',
    solution: [],
    statementWriteOffCode: '',
    templateVos: [],
  })

  /**
   * 申请结单
   * @param {string} orderId - 工单id
   */
  const apply = async (orderId: string) => {
    applyLoading.value = true
    const res = await engineerEndOrderApply(applyForm.value, orderId)
    applyLoading.value = false
    return res.data
  }

  return {
    applyForm,
    applyLoading,
    apply,
  }
}

/**
 * 确定领料（网点角色使用）
 */
export const useEngineerTakeMaterialConfirm = () => {
  // 领料加载
  const takeMaterialLoading = ref(false)

  /**
   * 确认领料
   * @param {string} id - 工单id
   */
  const takeMaterial = async (id: string) => {
    takeMaterialLoading.value = true
    const res = await engineerTakeMaterialConfirm(id)
    takeMaterialLoading.value = false
    return res.data
  }

  return {
    takeMaterialLoading,
    takeMaterial,
  }
}

/**
 * 更新百事工单状态
 */
export const useUpdateBaishiOrderStatus = () => {
  // 更新加载
  const updateLoading = ref(false)

  /**
   * 更新表单
   */
  const updateForm = ref<OrderAPIRequest.UpdateBaishiOrderStatus>({
    orderStatus: '',
    remark: '',
    orderStatusNodeCode: '',
    orderStatusNodeName: '',
  })

  /**
   * 更新
   * @param {string} orderId - 工单id
   */
  const update = async (orderId: string) => {
    updateLoading.value = true
    const res = await updateBaishiOrderStatus(orderId, updateForm.value)
    updateLoading.value = false
    return res.data
  }

  /**
   * 重置表单
   */
  const resetForm = () => {
    updateForm.value = {
      orderStatus: '',
      remark: '',
      orderStatusNodeCode: '',
      orderStatusNodeName: '',
    }
  }

  return {
    updateForm,
    updateLoading,
    update,
    resetForm,
  }
}

/**
 * 获取修改前的工单客户信息
 */
export const useGetOrderUserInfoBeforeUpdate = () => {
  // 获取信息加载
  const getInfoLoading = ref(false)

  // 修改前的工单客户信息
  const info = ref<OrderUserInfoBeforeUpdate>({
    address: '',
    area: '',
    businessPhone: '',
    city: '',
    id: '',
    name: '',
    otherPhone: '',
    phone: '',
    province: '',
    sendForRepairPhone: '',
    sendForRepairUsername: '',
    storeName: '',
    town: '',
  })

  /**
   * 获取信息
   * @param {string} orderId - 工单id
   */
  const getInfo = async (orderId: string) => {
    getInfoLoading.value = true
    const res = await getBeforeUpdateWorkUserInfo(orderId)
    getInfoLoading.value = false
    if (res.data.code === 20000) {
      info.value = res.data.data.row
    }
  }

  return {
    info,
    getInfoLoading,
    getInfo,
  }
}

/**
 * 更新工单客户信息
 */
export const useUpdateOrderUserInfo = () => {
  // 更新加载
  const updateLoading = ref(false)

  // 更新表单
  const updateForm = ref<OrderAPIRequest.UpdateOrderUserInfo>({
    address: '',
    area: '',
    businessPhone: '',
    city: '',
    helpOtherCreateOrder: 0,
    name: '',
    otherPhone: '',
    phone: '',
    province: '',
    repairCompany: '',
    repairCompanyId: '',
    repairCompanyPhone: '',
    sendForRepairPhone: '',
    sendForRepairUsername: '',
    storeName: '',
    town: '',
    userId: '',
    id: '',
  })

  /**
   * 更新
   */
  const update = async () => {
    updateLoading.value = true
    const res = await saveUpdateWorkUser(updateForm.value)
    updateLoading.value = false
    return res.data
  }

  /**
   * 重置表单
   */
  const resetForm = () => {
    updateForm.value = {
      address: '',
      area: '',
      businessPhone: '',
      city: '',
      helpOtherCreateOrder: 0,
      name: '',
      otherPhone: '',
      phone: '',
      province: '',
      repairCompany: '',
      repairCompanyId: '',
      repairCompanyPhone: '',
      sendForRepairPhone: '',
      sendForRepairUsername: '',
      storeName: '',
      town: '',
      userId: '',
      id: '',
    }
  }

  return {
    updateForm,
    updateLoading,
    update,
    resetForm,
  }
}

/**
 * 获取工单结单状态
 */
export const useGetOrderEndStatus = () => {
  // 获取状态加载
  const getStatusLoading = ref(false)

  // 结单状态
  // true - 已申请结单
  // false - 未申请结单
  const status = ref(false)

  /**
   * 获取结单状态
   * @param {string} id - 工单id
   */
  const getStatus = async (id: string) => {
    getStatusLoading.value = true
    const res = await getOrderEndStatus(id)
    getStatusLoading.value = false
    if (res.data.code === 20000) {
      status.value = res.data.data
      return ''
    }
    return res.data.message
  }

  return {
    status,
    getStatusLoading,
    getStatus,
  }
}

/**
 * 获取工单结单列表
 */
export const useGetOrderEndFieldList = () => {
  // 获取列表加载
  const getListLoading = ref(false)

  // 字段列表
  const fieldList = ref<OrderEndFieldListItem['objects']>([])

  /**
   * 获取字段列表
   * @param {string} id - 工单id
   */
  const getList = async (id: string) => {
    getListLoading.value = true
    const res = await getEndOrderFieldList(id)
    getListLoading.value = false
    if (res.data.code === 20000) {
      fieldList.value = res.data.data.objects
      return ''
    }

    return res.data.message
  }

  /**
   * 重置字段列表
   */
  const resetFieldList = () => {
    fieldList.value.length = 0
  }

  return {
    fieldList,
    getListLoading,
    getList,
    resetFieldList,
  }
}

/**
 * 工单结单信息保存
 */
export const useSaveOrderEndResult = () => {
  // 保存加载
  const saveLoading = ref(false)

  // 保存表单
  const saveForm = ref<OrderEndFieldListItem['objects']>([])

  /**
   * 重置表单
   */
  const resetForm = () => {
    saveForm.value.length = 0
  }

  /**
   * 保存
   * @param {string} id - 工单id
   * @param {0|1|2|3} type - 保存类型，0->申请 1->审核通过 2->审核驳回 3->保存并审核
   * @param {string} moduleId - 工单模块id
   */
  const save = async (id: string, type: 0 | 1 | 2 | 3, moduleId: string) => {
    saveLoading.value = true
    const res = await saveEndOrderResult(id, type, moduleId, saveForm.value)
    saveLoading.value = false
    return res.data
  }

  return {
    saveForm,
    saveLoading,
    resetForm,
    save,
  }
}

/**
 * 推送工单到电匠院
 */
export const usePushOrderToDianJiangYuan = () => {
  // 推送加载
  const pushLoading = ref(false)

  /**
   * 推送
   * @param {string} orderId - 工单id
   */
  const push = async (orderId: string) => {
    pushLoading.value = true
    const res = await pushOrderToDianJiangYuan(orderId)
    pushLoading.value = false
    return res.data
  }

  return {
    pushLoading,
    push,
  }
}

/**
 * 查询编码，用于更换条码
 */
export const useQueryCodeForUpdateGood = () => {
  // 查询加载
  const queryLoading = ref(false)

  // 查询条码
  const querySnCode = ref('')

  // 条码信息
  const snCodeInfoForUpdateCode = ref<OrderSnCodeInfoForUpdateCode>({
    activa: false,
    activaTime: '',
    archived: '',
    batchGoodsId: '',
    batchId: '',
    blacklist: false,
    buyMarket: '',
    codeSource: '',
    createEmp: '',
    createEmpId: '',
    custAccId: '',
    dateOfProduction: '',
    disabled: '',
    gmtCreate: '',
    gmtUpdate: '',
    goodsId: '',
    goodsSpecId: '',
    id: '',
    lotNo: '',
    network: '',
    networkId: '',
    outStoreActiva: '',
    outStoreWarranty: '',
    outboundStoreNumber: '',
    produceDate: '',
    remainingWarrantyDay: '',
    remark: '',
    register: {
      address: '',
      area: '',
      city: '',
      custAccId: '',
      gmtCreate: '',
      gmtUpdate: '',
      id: '',
      name: '',
      phone: '',
      province: '',
      town: '',
      userId: '',
    },
    saleNetworkName: '',
    saleNetworkNumber: '',
    salePrice: '',
    securityCode: '',
    sendGoodsNumber: '',
    status: 0,
    storeCode: '',
    storeId: '',
    storePositionId: '',
    storeStatus: 0,
    spec: {
      code: '',
      custAccId: '',
      enabled: false,
      gmtCreate: '',
      gmtUpdate: '',
      id: '',
      image: '',
      name: '',
      overPrice: 0,
      price: 0,
      productId: '',
      warrantyDay: 0,
    },
    type: 0,
    updateEmp: '',
    updateEmpId: '',
    user: {
      account: '',
      avatar: '',
      blacklist: false,
      code: '',
      createEmpId: '',
      creditLimit: 0,
      creditLimitType: 0,
      custAccId: '',
      gmtCreate: '',
      gmtUpdate: '',
      id: '',
      lastLoginTime: '',
      level: '',
      levelId: '',
      money: 0,
      name: '',
      nickname: '',
      password: '',
      phone: '',
      salt: '',
      selectKnowledgeAuthor: false,
      settlementDeadline: 0,
      status: 0,
      updateEmpId: '',
      userType: '',
      userTypeId: '',
    },
    warrantyDay: 0,
    warrantyEndTime: '',
    warrantyStartTime: '',
    zjProduct: {
      ascriptionType: 0,
      brand: '',
      brandId: '',
      code: '',
      createEmpId: '',
      custAccId: '',
      deleted: false,
      disabled: false,
      enabledRegister: false,
      gmtCreate: '',
      gmtUpdate: '',
      id: '',
      itemNumber: '',
      model: '',
      name: '',
      qrImage: '',
      source: 0,
      type: '',
      typeId: '',
      typeThree: '',
      typeThreeId: '',
      typeTwo: '',
      typeTwoId: '',
      unit: '',
      unitId: '',
      updateEmpId: '',
      saleModels: '',
    },
    registerCode: null,
  })

  /**
   * 查询
   */
  const queryCode = async () => {
    queryLoading.value = true
    const res = await queryCodeForUpdateCode(querySnCode.value)
    queryLoading.value = false
    if (res.data.code === 20000) {
      snCodeInfoForUpdateCode.value = res.data.data
      return ''
    }
    return res.data.message
  }

  /**
   * 重置
   */
  const resetQuery = () => {
    querySnCode.value = ''
    snCodeInfoForUpdateCode.value = {
      activa: false,
      activaTime: '',
      archived: '',
      batchGoodsId: '',
      batchId: '',
      blacklist: false,
      buyMarket: '',
      codeSource: '',
      createEmp: '',
      createEmpId: '',
      custAccId: '',
      dateOfProduction: '',
      disabled: '',
      gmtCreate: '',
      gmtUpdate: '',
      goodsId: '',
      goodsSpecId: '',
      id: '',
      lotNo: '',
      network: '',
      networkId: '',
      outStoreActiva: '',
      outStoreWarranty: '',
      outboundStoreNumber: '',
      produceDate: '',
      remainingWarrantyDay: '',
      remark: '',
      register: {
        address: '',
        area: '',
        city: '',
        custAccId: '',
        gmtCreate: '',
        gmtUpdate: '',
        id: '',
        name: '',
        phone: '',
        province: '',
        town: '',
        userId: '',
      },
      saleNetworkName: '',
      saleNetworkNumber: '',
      salePrice: '',
      securityCode: '',
      sendGoodsNumber: '',
      status: 0,
      storeCode: '',
      storeId: '',
      storePositionId: '',
      storeStatus: 0,
      spec: {
        code: '',
        custAccId: '',
        enabled: false,
        gmtCreate: '',
        gmtUpdate: '',
        id: '',
        image: '',
        name: '',
        overPrice: 0,
        price: 0,
        productId: '',
        warrantyDay: 0,
      },
      type: 0,
      updateEmp: '',
      updateEmpId: '',
      user: {
        account: '',
        avatar: '',
        blacklist: false,
        code: '',
        createEmpId: '',
        creditLimit: 0,
        creditLimitType: 0,
        custAccId: '',
        gmtCreate: '',
        gmtUpdate: '',
        id: '',
        lastLoginTime: '',
        level: '',
        levelId: '',
        money: 0,
        name: '',
        nickname: '',
        password: '',
        phone: '',
        salt: '',
        selectKnowledgeAuthor: false,
        settlementDeadline: 0,
        status: 0,
        updateEmpId: '',
        userType: '',
        userTypeId: '',
      },
      warrantyDay: 0,
      warrantyEndTime: '',
      warrantyStartTime: '',
      zjProduct: {
        ascriptionType: 0,
        brand: '',
        brandId: '',
        code: '',
        createEmpId: '',
        custAccId: '',
        deleted: false,
        disabled: false,
        enabledRegister: false,
        gmtCreate: '',
        gmtUpdate: '',
        id: '',
        itemNumber: '',
        model: '',
        name: '',
        qrImage: '',
        source: 0,
        type: '',
        typeId: '',
        typeThree: '',
        typeThreeId: '',
        typeTwo: '',
        typeTwoId: '',
        unit: '',
        unitId: '',
        updateEmpId: '',
        saleModels: '',
      },
      registerCode: null,
    }
  }

  return {
    querySnCode,
    queryLoading,
    snCodeInfoForUpdateCode,
    resetQuery,
    queryCode,
  }
}

/**
 * 更新产品条码
 */
export const useUpdateGoodSncode = () => {
  // 更新加载
  const updateLoading = ref(false)

  // 更新表单
  const updateForm = ref<OrderAPIRequest.UpdateGoodSncode>({
    snCodes: [],
    workGoodsId: '',
  })

  /**
   * 更新
   * @param {string} orderId - 工单id
   */
  const update = async (orderId: string) => {
    updateLoading.value = true
    const res = await updateWorkGoodsBindSnCode(updateForm.value, orderId)
    updateLoading.value = false
    return res.data
  }

  /**
   * 重置表单
   */
  const resetForm = () => {
    updateForm.value = {
      snCodes: [],
      workGoodsId: '',
    }
  }

  return {
    updateForm,
    updateLoading,
    update,
    resetForm,
  }
}
